<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="10">
        <div class="panel-info">
          <div class="panel-title">目录流程树</div>
          <div class="panel-body">
            <div class="btn-group">
              <el-input style="width:180px;" placeholder="输入查询" prefix-icon="el-icon-search" v-model="filterText">
              </el-input>
              <el-button style="float:right" size="small" type="primary" v-permission="'process.add'"
                @click="createFlow" title="添加目录或流程">
                添加目录/流程
              </el-button>
            </div>
            <div class="tree-content">
              <el-tree :data="treeData" draggable style="font-size:13px" :allow-drop="treeAllowDrop"
                @node-drag-end="treeHandleDragEnd" :allow-drag="treeAllowDrag" :default-expand-all="true"
                @node-drag-start="treeHandleDragStart" :props="defaultProps" :filter-node-method="filterNode"
                class="filter-tree" @node-click="treeHandleNodeClick" :highlight-current="true" ref="tree">
                <span slot-scope="{ node, data }">
                  <i class="el-icon-folder" style="vertical-align: top" v-show="data.type==1"></i><i
                    class="el-icon-document" style="vertical-align: top" v-show="data.type==2"></i><span
                    :title="node.label" class="span-ellipsis">&nbsp;<span v-if="data.enabled==2"
                      style="color:#F56C6C">{{node.label}}</span>
                    <span v-else>{{node.label}}</span></span>
                </span>
              </el-tree>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="14" v-if="editModel || (!!flowData.id && flowData.type==2) ">
        <div class="panel-info">
          <div class="panel-title">目录详情设置</div>
          <div class="panel-body">
            <div class="right-content" v-show="editModel">
              <div class="btn-group" style="padding-right: 40px;">
                <el-button size="small" type="danger" v-permission="'process.delete'" @click="deleteFloderOrRouteInfo"
                  plain>
                  删除</el-button>
                <el-button style="float:right" type="primary" v-permission="'process.edit'"
                  @click.native="addFolderOrRoute" :loading="submitLoading">保存
                </el-button>
              </div>
              <div style="padding-right: 40px;margin-top:20px;">
                <el-form :model="flowData" label-width="100px">
                  <el-form-item v-if="!!flowData.id && flowData.type==2" label="">
                    <el-button type="success" @click.native="goDetail" v-permission="'process.edit'"
                      :loading="submitLoading" plain>
                      流程节点设置
                    </el-button>
                    <el-dropdown class="ml-5" @command="changeVersion" v-permission="'process.edit'">
                      <el-button type="info" plain>
                        查看历史版本<i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="it in flowData.versions" :key="it.id" :command="it.id"
                          :class="{'text-gary':it.enabled==2}">{{it.version}}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <el-button class="ml-5" type="warning" v-permission="'process.edit'" plain @click="addNewVersion">
                      流程升版
                    </el-button>
                  </el-form-item>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="类型">
                        <el-select v-model="flowData.type" :disabled="!!flowData.id" style="width: 100%"
                          placeholder="请选择类型">
                          <el-option label="目录" :value="1" :key="1"></el-option>
                          <el-option label="流程" :value="2" :key="2"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="flowData.type == 1" :span="24">
                      <el-form-item label="目录名称">
                        <el-input v-model="flowData.route_name"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col v-else :span="12">
                      <el-form-item label="流程序号">
                        <el-input v-model="flowData.route_code" disabled></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <template v-if="flowData.type == 2">
                    <el-form-item label="工艺名称">
                      <el-input v-model="flowData.route_name"></el-input>
                    </el-form-item>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="工艺版本">
                          <el-input v-model="flowData.version"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item v-if="flowData.id" label="已启用">
                          <el-switch v-model="flowData.enabled" :active-value="1" :inactive-value="2"
                            @change="forbidden">
                          </el-switch>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col v-if="flowData.id"
                        :span="flowData.id && flowData.control_type && flowData.control_type!=1?20:24">
                        <el-form-item label="适用类型">
                          <el-select v-model="flowData.control_type" @change="controlTypeChange" style="width: 100%"
                            placeholder="请选择">
                            <el-option label="通用流程" :value="1"></el-option>
                            <el-option label="按适用机种" :value="2"></el-option>
                            <el-option label="按适用型号" :value="3"></el-option>
                          </el-select>
                        </el-form-item>
                        <!--<el-form-item v-show="flowData.control_type==2 || flowData.control_type==3"
                                                  label="适用机种">
                                        <el-select v-model="flowData.sku" :filterable="true" @change="skuChange()"
                                                   style="width:100%" multiple
                                                   placeholder="请选择机种">
                                            <el-option v-for="item in skuoptions" :key="item.value" :label="item.label"
                                                       :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>-->
                      </el-col>
                      <el-col v-if="flowData.id && flowData.control_type!=1 && flowData.control_type" :span="4">
                        <el-button style="margin-left: 5px" type="primary" plain @click="bindSku()">
                          <span>{{flowData.control_type == 2 ? '绑定机种' : '绑定型号'}}</span>
                        </el-button>
                      </el-col>
                    </el-row>

                    <!--<el-form-item v-show="flowData.control_type==3" label="适用型号">
                                <el-select v-model="flowData.sku_type" @change="skuTypeChange" :filterable="true"
                                           style="width:100%"
                                           multiple placeholder="请选择">
                                    <el-option v-for="item in skutypeoptions" :key="item.value" :label="item.label"
                                               :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>-->
                    <el-form-item label="备注">
                      <el-input type="textarea" rows="3" v-model="flowData.remarks"></el-input>
                    </el-form-item>
                  </template>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <div v-loading="loading" class="flex">
      <el-dialog title="流程升版" width="65%" :close-on-click-modal="false" :visible.sync="addVersinModalVisible">
        <div style="padding-right: 80px;">
          <el-form :model="newVersionData" label-width="100px">
            <el-form-item label="流程名称">
              <el-input v-model="newVersionData.routeName" disabled></el-input>
            </el-form-item>
            <el-form-item label="原版本">
              <el-input v-model="newVersionData.oldVersion" disabled></el-input>
            </el-form-item>
            <el-form-item label="新版本">
              <el-input v-model="newVersionData.newVersion"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-checkbox v-model="newVersionData.disabledFlag">是否禁用原版本</el-checkbox>
            </el-form-item>
            <div>禁用后，新的工单上线将无法再选择旧版流程，但已上线的工单仍可按旧流程继续流转。</div>
            <div class="text-right dialog-footer">
              <el-button @click="addVersinModalVisible = false">取消</el-button>
              <el-button type="primary" @click.native="addNewVersionSubmit()" :loading="submitLoading">
                确认
              </el-button>
            </div>
          </el-form>
        </div>
      </el-dialog>

      <!--机种型号绑定-->
      <el-dialog width="90%" :visible.sync="bindSkuModalShow" :close-on-click-modal="false">
        <div class="flex" style="margin-top:-20px;">
          <div class="flex1">
            <div class="flex" style="justify-content:space-between; align-items: center; padding-bottom: 10px;">
              <label>{{this.flowData.control_type == 2 ? '可绑机种' : '可绑型号'}}</label>
              <el-select v-show="flowData.control_type==3" v-model="canBindSkuParams.query.models" :filterable="true"
                @change="getUnbindModelsList(true)" style="width:300px" multiple placeholder="请选择机种">
                <el-option v-for="item in skuoptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <el-input style="width: 180px;margin-left: 5px" placeholder="输入查询条件按回车" clearable
                prefix-icon="el-icon-search" @keyup.enter.native="getUnbindModelsList(true)"
                @clear="getUnbindModelsList(true)" v-model="canBindSkuParams.query.queryString">
              </el-input>
            </div>
            <el-table :data="canBindSkuList" border style="width: 100%" @selection-change="canBindSelectionChange">
              <el-table-column type="selection" width="40" show-overflow-tooltip></el-table-column>
              <el-table-column prop="model_code" label="机种编号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="model_name" label="机种名称" show-overflow-tooltip></el-table-column>
              <div v-show="flowData.control_type==3">
                <el-table-column prop="key_part_no" label="产品编码" show-overflow-tooltip></el-table-column>
                <el-table-column prop="key_part_name" label="产品名称" show-overflow-tooltip></el-table-column>
                <el-table-column prop="brief_code" label="产品简码" show-overflow-tooltip></el-table-column>
              </div>
            </el-table>
            <z-pagination :pagination="bindSkuPagination" :total="canBindSkuTotal" :page.sync="canBindSkuParams.page"
              :limit.sync="canBindSkuParams.size" @change="getUnbindModelsList()">
            </z-pagination>
          </div>
          <div style="padding:20px;">
            <div style="margin-top:60px">
              <el-button type="success" icon="el-icon-d-arrow-right" @click="bindCommit"
                :disabled="canBindSelections.length == 0" :loading="bindLoading" circle></el-button>
            </div>
            <div style="margin-top:60px">
              <el-button type="danger" icon="el-icon-d-arrow-left" @click="cancelBindCommit"
                :disabled="cancelBindSelectons.length == 0" :loading="bindLoading" circle></el-button>
            </div>
          </div>
          <div class="flex1">
            <div class="flex" style="justify-content:space-between; align-items: center; padding-bottom: 10px;">
              <label>{{this.flowData.control_type == 2 ? '已绑机种' : '已绑型号'}}</label>
              <el-input style="width: 180px;" placeholder="输入查询条件按回车" clearable prefix-icon="el-icon-search"
                @keyup.enter.native="getBindModelsList(true)" @clear="getBindModelsList(true)"
                v-model="boundSkuParams.query.queryString">
              </el-input>
            </div>
            <el-table :data="boundSkuList" border style="width: 100%" @selection-change="cancelBindSelectionChange">
              <el-table-column type="selection" width="40" show-overflow-tooltip></el-table-column>
              <el-table-column prop="model_code" label="机种编号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="model_name" label="机种名称" show-overflow-tooltip></el-table-column>
              <div v-show="flowData.control_type==3">
                <el-table-column prop="key_part_no" label="产品编码" show-overflow-tooltip></el-table-column>
                <el-table-column prop="key_part_name" label="产品名称" show-overflow-tooltip></el-table-column>
                <el-table-column prop="brief_code" label="产品简码" show-overflow-tooltip></el-table-column>
              </div>
            </el-table>
            <z-pagination :pagination="bindSkuPagination" :total="boundSkuTotal" :page.sync="boundSkuParams.page"
              :limit.sync="boundSkuParams.size" @change="getBindModelsList()">
            </z-pagination>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import zPagination from '@/views/_common/pagination'
import _ from 'lodash'

const flowData = { enabled: 1, type: 2, route_code: null }

export default {
  name: 'process',
  components: { zPagination },
  data() {
    return {
      api: this.$api.design,
      flowData: { ...flowData },
      skuoptions: [],
      skutypeoptions: [],
      treeData: [], //左侧目录
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      filterText: '', //流程、目录筛选
      nodeFlag: false, //判断目录节点是否允许放置
      list: [],
      flowFileId: '', //流程id
      submitLoading: false,
      loading: false,
      deleteLoading: false,
      editModel: false,
      newVersionData: {},
      addVersinModalVisible: false,

      //机种型号选择
      bindSkuModalShow: false,
      bindSkuTableProps: { border: true, hideOperations: true },
      bindSkuPagination: {
        layout: 'prev, pager, next, ->, total, sizes',
      },
      bindSkuColumns: [
        { title: '机种编号', key: 'model_code' },
        { title: '机种名称', key: 'model_name' },
        { title: '产品编码', key: 'key_part_no' },
        { title: '产品名称', key: 'key_part_name' },
        { title: '产品简码', key: 'brief_code' },
      ],
      canBindSkuList: [],
      canBindSkuTotal: 0,
      canBindSkuParams: {
        page: 1,
        size: 10,
        query: { queryString: '', models: [], id: '' },
      },
      boundSkuList: [],
      boundSkuTotal: 0,
      boundSkuParams: {
        page: 1,
        size: 10,
        query: { queryString: '', code: '', id: '' },
      },
      canBindSelections: [],
      cancelBindSelectons: [],
      bindLoading: false,
    }
  },
  methods: {
    bindSku() {
      this.canBindSkuParams.query.id = this.flowData.id
      this.boundSkuParams.query.id = this.flowData.id
      this.canBindSkuParams.page = 1
      this.boundSkuParams.page = 1
      this.bindSkuModalShow = true
      //if(!this.canBindSkuParams.query.models || this.canBindSkuParams.query.models.length<=0)this.canBindSkuParams.query.models = this.flowData.sku
      this.getBindModelsList()
      this.getUnbindModelsList()
    },
    getBindModelsList(v) {
      if (v) this.boundSkuParams.page = 1
      this.boundSkuList = []
      this.boundSkuTotal = 0
      let url = this.api
      if (this.flowData.control_type == 2) url += 'getBindModelsList'
      if (this.flowData.control_type == 3) url += 'getBindSkuTypeList'
      this.$request(url, this.boundSkuParams).then((r) => {
        this.boundSkuList = r.list
        this.boundSkuTotal = r.total
      })
    },
    getUnbindModelsList(v) {
      console.log(this.canBindSkuParams)
      if (v) this.canBindSkuParams.page = 1
      this.canBindSkuTotal = 0
      this.canBindSkuList = []
      let url = this.api
      if (this.flowData.control_type == 2) url += 'getUnbindModelsList'
      if (this.flowData.control_type == 3) url += 'getUnbindSkuTypeList'
      this.$request(url, this.canBindSkuParams).then((r) => {
        this.canBindSkuList = r.list
        this.canBindSkuTotal = r.total
      })
    },
    bindCommit() {
      this.bindLoading = true
      this.$request(
        this.api + 'bindSku',
        {
          id: this.flowData.id,
          control_type: this.flowData.control_type,
          sku_ids: this.canBindSelections,
        },
        'POST',
      )
        .then((r) => {
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.bindLoading = false
          this.canBindSelections = []
          this.bindSku()
        })
        .catch((e) => {
          this.bindLoading = false
        })
    },
    cancelBindCommit() {
      this.bindLoading = true
      this.$request(
        this.api + 'unbindSku',
        {
          usage_ids: this.cancelBindSelectons,
        },
        'POST',
      )
        .then((r) => {
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.bindLoading = false
          this.cancelBindSelectons = []
          this.bindSku()
        })
        .catch((e) => {
          this.bindLoading = false
        })
    },
    canBindSelectionChange(v) {
      this.canBindSelections = v.map((i) => i.id)
    },
    cancelBindSelectionChange(v) {
      this.cancelBindSelectons = v.map((i) => i.id)
    },
    createFlow() {
      this.flowData = { ...flowData }
      this.editModel = true
      this.getRouteCode()
    },
    getRouteCode() {
      this.$request(this.api + 'getRouteCode')
        .then((r) => {
          this.flowData.route_code = r.code
        })
        .catch(() => {})
    },
    controlTypeChange() {
      if (!this.flowData.id) return
      this.canBindSkuParams = {
        page: 1,
        size: 10,
        query: { queryString: '', models: [], id: '' },
      }
      this.boundSkuParams = {
        page: 1,
        size: 10,
        query: { queryString: '', code: '', id: '' },
      }

      this.$request(
        this.api + 'updateRouteControlType',
        {
          id: this.flowData.id,
          control_type: this.flowData.control_type,
        },
        'POST',
      )
        .then((r) => {
          this.$message({
            message: '适用类型切换成功',
            type: 'success',
          })
        })
        .catch((e) => {})
    },
    changeVersion(id) {
      this.flowFileId = id
      this.getRouteById()
    },
    getRouteById() {
      this.flowData.controlFlag = false
      this.$request(this.api + 'getRouteById', { id: this.flowFileId })
        .then((r) => {
          console.log(r)
          this.flowData = r
          this.flowData.controlFlag = false
        })
        .catch(() => {})
    },
    addFolderOrRoute() {
      this.submitLoading = true
      if (!this.flowData.controlFlag) this.flowData.parent_id = this.flowFileId
      this.$request(this.api + 'addFolderOrRoute', this.flowData, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editModel = false
          this.getFolderOrRoute()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    getFolderOrRoute() {
      this.$request(this.api + 'getFolderOrRoute')
        .then((r) => {
          this.treeData = r
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    addNewVersion() {
      this.newVersionData = {
        sourceId: this.flowData.id,
        routeName: this.flowData.route_name,
        oldVersion: this.flowData.version,
        newVersion: '',
        disabledFlag: true,
      }
      this.addVersinModalVisible = true
    },
    addNewVersionSubmit() {
      this.submitLoading = true
      console.log('this.newVersionData', this.newVersionData)
      let formData = new FormData()
      formData.append('sourceId', this.newVersionData.sourceId)
      formData.append('newVersion', this.newVersionData.newVersion)
      formData.append('disabledFlag', this.newVersionData.disabledFlag)
      this.$request(this.api + 'addNewVersionRoute', formData, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.addVersinModalVisible = false
          this.flowFileId = r
          this.getRouteById()
          this.getFolderOrRoute()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    //树相关
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    treeAllowDrag(draggingNode) {
      return true
    },
    treeHandleDragStart(node, ev) {
      this.flowFileId = null
      this.editModel = false
    },
    treeHandleNodeClick(data) {
      this.canBindSkuParams = {
        page: 1,
        size: 10,
        query: { queryString: '', models: [], id: '' },
      }
      this.boundSkuParams = {
        page: 1,
        size: 10,
        query: { queryString: '', code: '', id: '' },
      }
      this.flowFileId = data.sid
      if (data.type == 2) {
        this.editModel = true
        this.getRouteById()
      } else {
        this.flowData = {
          id: data.sid,
          type: data.type,
          enabled: data.enabled,
          id: data.sid,
          route_name: data.label,
        }
        this.editModel = true
      }
    },
    treeAllowDrop(draggingNode, dropNode, type) {
      if (dropNode.data.type == 2 && type == 'inner') {
        this.nodeFlag = true
        return false
      }
      this.nodeFlag = false
      return true
    },
    treeHandleDragEnd(draggingNode, dropNode, dropType, ev) {
      if (this.nodeFlag && dropType == 'inner') {
        this.$message({
          message: '具体流程下不能放置文件/目录',
          type: 'error',
        })
        return false
      }
      if (dropType == 'none') {
        return false
      }
      let data = { dropId: dropNode.data.sid, id: draggingNode.data.sid, type: dropType, allData: this.treeData }
      this.$request(this.api + 'updateParent', data, 'post').then((r) => {})
    },
    deleteFloderOrRouteInfo() {
      if (!this.flowFileId) {
        this.$message({
          message: '请先选择目录/流程',
          type: 'error',
        })
        return false
      }
      this.$confirm('确定要删除这条记录？', '操作确认').then(() => {
        this.deleteLoading = true
        this.$request(this.api + 'delete/' + this.flowFileId, {}, 'post')
          .then((r) => {
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.deleteLoading = false
            this.editModel = false
            this.flowFileId = null
            this.getFolderOrRoute()
          })
          .catch(() => {
            this.deleteLoading = false
          })
      })
    },
    forbidden() {
      if (!this.flowFileId) {
        this.$message({
          message: '请先选择流程',
          type: 'error',
        })
        return false
      }
      this.$request(this.api + 'forbidden/' + this.flowFileId, {}, 'post').then((r) => {
        this.$message({
          message: '操作成功',
          type: 'success',
        })
        this.getFolderOrRoute()
      })
    },
    skuChange() {
      this.skutypeoptions = []
      /*this.$request(this.$api.sku + 'getlist/bymodel?modellist=' + this.flowData.sku).then((r) => {
          let tmp = []
          r.datas.forEach(function (v) {
            tmp.push({label: v.key_part_name + ' ' + v.version, value: v.id})
          })
          this.skutypeoptions = tmp
        })*/
    },
    skuTypeChange() {
      this.$forceUpdate()
    },
    goDetail() {
      this.$store.dispatch('delView', { name: 'processDetail' }).then((r) => {
        this.$router
          .push({
            name: 'processDetail',
            params: {
              id: this.flowFileId,
            },
          })
          .catch(() => {})
      })
    },
  },
  created() {
    this.getFolderOrRoute()
    this.$request(this.$api.model + 'getseries').then((r) => {
      let tmp = []
      r.forEach(function (v) {
        tmp.push({ label: v.model_name + ' ' + v.model_code, value: v.id })
      })
      this.skuoptions = tmp
    })
  },
  mounted() {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
}
</script>

<style lang="scss" scoped>
.panelTree {
  width: 40%;
  padding: 15px;
  border-right: 1px solid #e4e4e4;
  border-bottom: 1px solid #e4e4e4;
  max-height: calc(100vh - 86px);
  overflow-y: scroll;
}

.btn-group {
  padding-left: 20px;
}

.tree-content {
  margin-top: 20px;
}

.right-content {
  flex: 1;
  padding: 15px;
}

.zFormItem {
  display: inline-block;
  width: 49%;
}
</style>
